/*
 * @Author: 刘晟勇
 * @Date: 2021-10-12 18:52:24
 * @LastEditTime: 2021-10-23 13:53:22
 * @Description: file content
 */
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 引入api
import {
  getShopCartList
} from "@/api/auth"
import {
  getUserInfo
} from "@/api/auth"

export default new Vuex.Store({
  state: {
    token: sessionStorage.getItem('token') ? sessionStorage.getItem('token') :
      '',
    isLogin: sessionStorage.getItem('isLogin') ? sessionStorage.getItem('token') :
      false,
    userInfo: '',
    shopCartList: []
  },
  getters: {
    // 是否全选
    allChecked(state) {
      return state.shopCartList.every(item => {
        return item.checked === true
      }) ? true : false
    },
    // 总价格
    allPrice(state) {
      let price = 0
      state.shopCartList.forEach(item => {
        if (item.checked) {
          price += item.price * item.count
        }
      })
      return price * 100
    }
  },
  mutations: {
    // 设置登录状态
    setLoginStatue(state, value) {
      state.token = value.token
      state.isLogin = value.isLogin
      sessionStorage.setItem('token', value.token)
      sessionStorage.setItem('isLogin', value.isLogin)
    },
    // 设置用户信息
    setUserInfo(state, value) {
      state.userInfo = value
    },
    // 设置购物车列表
    setShopCartList(state, value) {
      state.shopCartList = value
    },
    // 全选方法
    changeAllChecked(state, value) {
      state.shopCartList = state.shopCartList.map(item => {
        item.checked = value
        return item
      })
    }
  },
  actions: {
    // 获取用户信息
    getInfo(context) {
      getUserInfo((data) => {
        console.log(data);
        context.commit('setUserInfo', data)
      })
    },
    // 获取购物车信息
    getShopCartData(context) {
      getShopCartList((data) => {
        // 添加checked属性
        const shopCartList = data.map(item => {
          item.checked = false
          return item
        })
        context.commit('setShopCartList', shopCartList)
      })
    }
  }
})